package util.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liming on 2017/1/16.
 */
public class ExcelUtil {

    private final static String excel2003L = ".xls";    //2003- 版本的excel
    private final static String excel2007U = ".xlsx";   //2007+ 版本的excel

    /**
     * 读取Excel数据内容
     *
     * @return Map 包含单元格数据内容的Map对象
     */
    public static List<List<Map<String, Object>>> readExcelContent(FileInputStream fileInputStream, String fileName) throws Exception {
        List<List<Map<String, Object>>> sheets = new ArrayList<>();
        Workbook work = null;
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        work = getWorkbook(fileInputStream, fileName);
        if (work == null) {
            throw new Exception("导入excel工作簿为空!");
        }
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {

            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            //遍历所有的列
            List<Map<String, Object>> li = new ArrayList<>();
            row = sheet.getRow(sheet.getFirstRowNum());
            if (row == null)
                continue;
            String[] keys = new String[row.getLastCellNum() - row.getFirstCellNum()];
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                keys[j] = row.getCell(j).getStringCellValue();
            }
            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum() + 1; j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null) {
                    continue;
                }
                Map<String, Object> rowMap = new HashMap<>();

                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    if (cell != null)
                        rowMap.put(keys[y], getCellValue(cell));
                }
                li.add(rowMap);
            }
            sheets.add(li);
        }

        work.close();
        return sheets;
    }

    /**
     * 描述：对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public static Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        if (CellType.STRING.equals(cell.getCellTypeEnum())) {
            value = cell.getRichStringCellValue().getString();
        } else if (CellType.NUMERIC.equals(cell.getCellTypeEnum())) {
            if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                value = df.format(cell.getNumericCellValue());
            } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                value = sdf.format(cell.getDateCellValue());
            } else {
                value = df2.format(cell.getNumericCellValue());
            }
        } else if (CellType.BOOLEAN.equals(cell.getCellTypeEnum())) {
            value = cell.getBooleanCellValue();
        } else if (CellType.BLANK.equals(cell.getCellTypeEnum())) {
            value = "";
        }
        return value;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr);  //2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr);  //2007+
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }


}